package cn.iocoder.yudao.module.digital.convert;

import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserNameConverter implements Converter<String>, ApplicationContextAware {
    
    private static AdminUserApi adminUserApi;
    private static ApplicationContext applicationContext;
    private static volatile Map<Long, AdminUserRespDTO> userCache;
    private static final Object LOCK = new Object();
    
    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }
    
    private static synchronized AdminUserApi getAdminUserApi() {
        if (adminUserApi == null) {
            adminUserApi = applicationContext.getBean(AdminUserApi.class);
        }
        return adminUserApi;
    }

    //做cache，免得每次都去查库
    private static AdminUserRespDTO getUserFromCache(Long userId) {
        if (userCache == null) {
            synchronized (LOCK) {
                if (userCache == null) {
                    userCache = new ConcurrentHashMap<>();
                }
            }
        }
        
        AdminUserRespDTO user = userCache.get(userId);
        if (user == null) {
            Map<Long, AdminUserRespDTO> newUsers = getAdminUserApi().getUserMap(Collections.singleton(userId));
            if (newUsers != null && !newUsers.isEmpty()) {
                user = newUsers.get(userId);
                if (user != null) {
                    userCache.put(userId, user);
                }
            }
        }
        return user;
    }

    public static void clearCache() {
        userCache = null;
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                GlobalConfiguration globalConfiguration) {
        throw new UnsupportedOperationException("暂不支持导入");
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
                                           GlobalConfiguration globalConfiguration) {
        if (!StringUtils.hasText(value)) {
            return new WriteCellData<>("");
        }
        try {
            // 尝试将字符串转换为 Long 类型的用户ID
            Long userId = Long.valueOf(value);
            // 从缓存获取用户信息
            AdminUserRespDTO user = getUserFromCache(userId);
            if (user == null) {
                return new WriteCellData<>(value);
            }
            // 返回 昵称(用户名) 格式
            return new WriteCellData<>(user.getNickname() + "(" + user.getUsername() + ")");
        } catch (NumberFormatException e) {
            // 如果转换失败，直接返回原值
            return new WriteCellData<>(value);
        }
    }
}
